/*
 * @Author: kanglang
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-08-12 14:34:45
 * @Description: 车主端首页
 */

import React from 'react';
import { SafeAreaView, StyleSheet, DeviceEventEmitter, NativeModules } from 'react-native';
import { WatermarkCameraView, msg } from '@/common';
import { mainBgColorLightGray, isAndroid, } from '@/styles';
import { uploadImage } from '@/config';
import api from '@/api';

export default class WatermarkCamera extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isPending: false
    };
  }

  componentDidMount() {
    this.onListenerAndroidAndIOS();
    this.getDriverInof();
  }

  componentWillUnmount() {
    this.listener && this.listener.remove();
    this.fileListener && this.fileListener.remove();
    this.refs.WaterCameraView.nativeMethod('onDestroy');
  }

  // 安卓回调监听
  onListenerAndroidAndIOS = () => {
    this.listener = DeviceEventEmitter.addListener('waterFinish', () => {
      msg.emit('router: back');
    });
    this.listener = DeviceEventEmitter.addListener('waterHistory', () => {
      msg.emit('router: goToNext', {
        routeName: 'WatermarkCameraHistoryRecords',
      });
      // msg.emit('router: back');WatermarkCameraHistoryRecords
    });

    this.fileListener = DeviceEventEmitter.addListener('USER_WATER_CAMERA', (resJson) => {
      const { isPending } = this.state;
      if (isPending) {
        return;
      }
      this.setState({ isPending: true });
      // 上传图片
      this.upLoadImage(JSON.parse(resJson));
    });
  };

  render() {
    return (
      <WatermarkCameraView
        style={{ flex: 1 }}
        ref='WaterCameraView'
      />
    );
  }

  // 上传图片
  upLoadImage = (dataDic) => {
    let path = dataDic.filePath;
    uploadImage('upload?dirName=waterImages', path).then(res => {
      if (res.success) {
        // 接口
        let param = { lat: dataDic.lat, lgt: dataDic.lng, pictureId: res.data.localId, uploadTime: dataDic.time, address: dataDic.address };
        api.supply.addDriverPictureInfo(param).then(picInfoRes => {
          if (picInfoRes.success) {
            NativeModules.DataModule.uploadWaterSuccess(JSON.stringify(dataDic));
            this.setState({ isPending: false });
            msg.emit('app:tip', { text: '上传成功' });
            msg.emit('router: back');
          } else {
            this._handleFailed(dataDic);
          }
        });
      } else {
        this._handleFailed(dataDic);
      }
    }).catch(err => {
      this._handleFailed(dataDic);
    });
  }

  _handleFailed=(dataDic) => {
    NativeModules.DataModule.saveWaterInfo(JSON.stringify(dataDic));
    // 请求失败
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '温馨提示',
      text: '网络不给力，图片将保存至相册，网络恢复后将自动上传',
      isClickBg: false,
      okFn: () => {
        msg.emit('router: back');
      },
    });
  }

  getDriverInof = () => {
    api.supply.getDriverCarDetail().then((res) => {
      if (res.success) {
        if (res.data) {
          this.refs.WaterCameraView.nativeMethod('receiveCarNum', [res.data.carNo]); // 这里初始化需要把车牌号传入
        }
      } else {
        msg.emit('app:tip', { text: res.msg || '网络异常' });
        // msg.emit('router: back');
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
});
